package com.chy.utilsdemo.validator;

import com.sunnada.gaia.commons.util.StringUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 功能：实体属性格式验证
 * <p>
 * ──────────────────────────────────────────
 * version  变更日期       修改人    修改说明
 * ------------------------------------------
 * V1.0.0   2022/8/15     CHY     初版
 * ──────────────────────────────────────────
 *
 * @author CHY
 */
public class ValidatorUtil {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    /**
     * 实体属性格式验证（一次性返回所有验证结果）
     *
     * @param t   实体集
     * @param <T> 实体
     * @return 返回结果
     */
    public static <T> String validates(T t) {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);

        List<String> messageList = new ArrayList<>();
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            messageList.add(constraintViolation.getMessage());
        }
        String error = "";
        if (messageList != null && messageList.size() > 0) {
            error = StringUtils.join(messageList, ";");
        }
        return error;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setName("");
        user.setMobile("4561253");
        user.setIdCard("11111111111111111111111111111111111111");
        String validates = validates(user);
        if (!StringUtil.isEmpty(validates)) {
            System.out.println("" + validates);
        }
    }


}
